/**
 *
 */
package com.storm.lib.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.storm.lib.type.Constant;
import com.storm.lib.type.SystemType;
import com.storm.lib.type.TemplateType;


/**
 * 类功能: 路径处理类
 * @author johnny
 * @version 2010-10-27
 */
public class FileUtil {
	protected final static Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 *
	 * 方法功能:返回源代码路径,需要在配置文件指定
	 * 更新时间:2010-10-27, 作者:johnny
	 * @param path 相对路径
	 * @return null 如果没找到,范例,com/mkyong/common/testing.txt
	 */
	public static String getCocoaFileSourcePoPath(String className,String prefix) {
		return getFileSourcePath()+"\\src\\com\\games\\rpg\\po\\cocoa\\"+className+"."+prefix;
	}

	/**
	 *
	 * 方法功能:返回应用路径
	 * 更新时间:2011-2-17, 作者:johnny
	 * @param filePath
	 * @return
	 */
	public static String getFileAppPath(String filePath){
		try {
			String path = BeanUtil.getApplicationContext().getResource(filePath).getFile().getAbsoluteFile().getPath();
			logger.debug(path);
			return path;
		} catch (IOException e) {
			ExceptionUtil.processPrintException(e);
		}
		return null;
	}

	/**
	 *
	 * 方法功能:返回文件路径
	 * 更新时间:2010-10-27, 作者:johnny
	 * @param path 相对路径
	 * @return null 如果没找到,范例,com/mkyong/common/testing.txt
	 */
	public static File getFileByClassPath(String classPath) {
		try {
			File file=BeanUtil.getApplicationContext().getResource("classpath:"+classPath).getFile();
			return file;
		} catch (IOException e) {
			ExceptionUtil.processPrintException(e);
		}
		return null;
	}

	/**
	 *
	 * 方法功能:返回源代码路径,需要在配置文件指定
	 * 更新时间:2010-10-27, 作者:johnny
	 * @param path 相对路径
	 * @return null 如果没找到,范例,com/mkyong/common/testing.txt
	 */
	public static String getFileSourcePath() {
		return System.getProperties().getProperty("user.dir")+"\\src\\";
	}

	public static String getFileBinPath() {
		return System.getProperties().getProperty("user.dir");
	}
	
	/**
	 *
	 * 方法功能:返回源代码路径,需要在配置文件指定
	 * 更新时间:2010-10-27, 作者:johnny
	 * @param path 相对路径
	 * @return null 如果没找到,范例,com/mkyong/common/testing.txt
	 */
	public static String getFileSourcePoPath(String className) {
		return getFileSourcePath()+"\\com\\games\\rpg\\po\\"+className+".java";
	}

	/**
	 * 方法功能:返回起始tag后的字符串
	 * 更新时间:2010-10-28, 作者:johnny
	 * @param templateStartTag
	 * @return
	 */
	public static String getFileStrByTag(File file,String templateStartTag) {
		String result="";
		Boolean start=false;
		if(file==null){
			ExceptionUtil.throwInvalidParamException();
		}
		BufferedReader input = null;
		try{
		    input = new BufferedReader(new FileReader(file));
		    String line=null;
			while ((line = input.readLine()) != null) {
				if(line.startsWith(TemplateType.TEMPLATE_START_TAG)){
					start=true;
					continue;
				}
				if(start==false){
					continue;
				}
				result+=line+"\n";
			}
		}catch (Exception e) {
			ExceptionUtil.processException(e);
		}
		finally{
			try {
				input.close();
			} catch (IOException e) {
				ExceptionUtil.processException(e);
			}
		}
		return result;
	}

	/**
	 * 方法功能:获得战报路径
	 * 更新时间:2011-2-17, 作者:johnny
	 * @return
	 */
	public static String getReportPath() {
//		logger.debug(FileUtil.getFileAppPath("/report/"));
		return FileUtil.getFileAppPath("\\report\\")+"\\";
	}

	/**
	 * 方法功能:获得商城XML路径
	 * 更新时间:2011-2-17, 作者:johnny
	 * @return
	 */
	public static String getUploadPath(Integer type) {
//		String path = "";
//		if(type.intValue()==1 || type.intValue()==2){//商城道具,数据库表地址
//			path = SystemType.DATA_UPLOAD_PATH;
//		}else if(type==3){//客户端国际化文本上传地址
//			path = SystemType.DATA_CLIENT_PATH;
//		}
		return SystemType.DATA_UPLOAD_PATH;
	}

	/**
	 * 方法功能:获得商城XML路径
	 * 更新时间:2011-2-17, 作者:johnny
	 * @return
	 */
	public static File getUnderGeneratorFile(String filename) {
//		return new File(SystemType.DATA_GENERATOR_PATH+filename);
		return null;
	}



	/**
	 *
	 * 方法功能:获得数据Excel的信息
	 * 更新时间:2011-2-18, 作者:johnny
	 * @param sheetName
	 * @return
	 */
	public static HSSFSheet getGameExcelDateSheet(String sheetName) {
		HSSFWorkbook workBook = getGameExcelData();
		HSSFSheet formulaSheet = workBook.getSheet(sheetName);
		return formulaSheet;
	}
	
	public static File getProtocalExcelFile() {
		File file=FileUtil.getUnderDataFile("protocol.xls");
		return file;
	}
	
	/**
	 *
	 * 方法功能:获得数据Excel的信息
	 * 更新时间:2011-2-18, 作者:johnny
	 * @param sheetName
	 * @return
	 */
	public static HSSFWorkbook getProtocalExcelData() {
		File file = getProtocalExcelFile();
		return getExcelByFile(file);
	}

	/**
	 * 获得伤害公式数据Excel的信息
	 * @return
	 */
	public static HSSFSheet getFormulaExcelDateSheet() {
		HSSFWorkbook workBook = getFormulaExcelData();
		HSSFSheet formulaSheet = workBook.getSheetAt(0);
		return formulaSheet;
	}

	public static HSSFSheet getInterSheetData(String sheetName){
		HSSFWorkbook workBook = FileUtil.getInterExcelData();
		if(null!=workBook){
			for(int i=0; i<workBook.getNumberOfSheets(); i++){
				HSSFSheet sheet = workBook.getSheetAt(i);
				if(sheetName.equals(sheet.getSheetName())){
					return sheet;
				}
			}
		}
		return null;
	}

	/**
	 *
	 * 方法功能:获得数据Excel的信息
	 * 更新时间:2011-2-18, 作者:johnny
	 * @param sheetName
	 * @return
	 */
	public static HSSFWorkbook getGameExcelData() {
		File file = getGameExcelFile();
		return getExcelByFile(file);
	}

	/**
	 *
	 * 方法功能:获得数据文件夹下的文件
	 * 更新时间:2011-2-18, 作者:johnny
	 * @param sheetName
	 * @return
	 */
	public static File getUnderDataFile(String fileName) {
		File file = FileUtil.getFileByClassPath(Constant.dataRelatedPath+fileName);
		return file;
	}
	/**
	 * 方法功能:获得数据文件下的lua
	 * @author future 2011-10-17
	 * @param fileName
	 * @return
	 */
	public static File getUnderDataLuaFile(String fileName) {
		File file = FileUtil.getFileByClassPath("com\\games\\rpg\\data\\lua\\"+fileName);
		return file;
	}
	/**
	 * 方法功能:获得数据文件下的lua
	 * @author future 2011-10-17
	 * @param fileName
	 * @return
	 */
	public static File getUnderDataDungeonFile() {
		File file = FileUtil.getFileByClassPath("com\\games\\rpg\\data\\dungeon\\");
		return file;
	}
	public static File getUnderConfigFile(String fileName) {
		File file = FileUtil.getFileByClassPath(Constant.configRelatedPath+fileName);
		return file;
	}

	public static File getGameExcelFile() {
		File file=FileUtil.getUnderDataFile("data.xls");
		return file;
	}

	public static HSSFWorkbook getExcelByFile(File file) {
		HSSFWorkbook workBook = getWorkbook(file);
		return workBook;
	}

	public static HSSFWorkbook getGameExcelData(String path) {
		File file=new File(path);
		HSSFWorkbook workBook = getWorkbook(file);
		return workBook;
	}

	/**
	 * 获得伤害公式数据Excel的信息
	 * @return
	 */
	public static HSSFWorkbook getFormulaExcelData() {
		File file=FileUtil.getFileByClassPath("com\\games\\rpg\\data\\Formula.xls");
		HSSFWorkbook workBook = getWorkbook(file);
		return workBook;
	}

	/**
	 * 获得国际化文本信息
	 * @return
	 */
	public static HSSFWorkbook getInterExcelData() {
		File file=getGameExcelFile();
		HSSFWorkbook workBook = getWorkbook(file);
		return workBook;
	}

	private static HSSFWorkbook getWorkbook(File file) {
		FileInputStream in=null;
		HSSFWorkbook workBook =null;
		try {
			in = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		try {
			workBook = new HSSFWorkbook(in);
		} catch (IOException e) {
			ExceptionUtil.processException(e);
		}
		return workBook;
	}

//	public static File getInterFile() {
//		File file=FileUtil.getFileByClassPath("com/games/rpg/data/data.xls");
//		return file;
//	}

	/**
	 * 以文件流的方式复制文件
     * @param srcPath 文件源目录
     * @param destPath 文件目的目录
     */
    public static void copyFile(String srcPath,String destPath){
    	FileInputStream in = null;
    	FileOutputStream out = null;
    	try {
	        in = new FileInputStream(srcPath);
	        File file=new File(destPath);
	        if(!file.exists())
	            file.createNewFile();
	        out=new FileOutputStream(file);
	        int c;
	        byte buffer[]=new byte[3072];
	        while((c=in.read(buffer))!=-1){
	            for(int i=0;i<c;i++)
	                out.write(buffer[i]);
	        }
	        in.close();
	        out.close();
		} catch (FileNotFoundException e) {
			ExceptionUtil.processException(e);
		} catch (IOException e) {
			ExceptionUtil.processException(e);
		}
    }

    public static void copyFileByCMD(String srcPath,String destPath){
//    	String cmd = "copy "+srcPath + " " + SystemType.DATA_BACKUP_PATH;
//    	try {
//			Runtime.getRuntime().exec(cmd);
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		}

//    	FileInputStream in = null;
//    	FileOutputStream out = null;
//    	try {
//	        in = new FileInputStream(srcPath);
//	        File file=new File(destPath);
//	        if(!file.exists())
//	            file.createNewFile();
//	        out=new FileOutputStream(file);
//	        int c;
//	        byte buffer[]=new byte[3072];
//	        while((c=in.read(buffer))!=-1){
//	            for(int i=0;i<c;i++)
//	                out.write(buffer[i]);
//	        }
//	        in.close();
//	        out.close();
//		} catch (FileNotFoundException e) {
//		ExceptionUtil.processException(e);
//		} catch (IOException e) {
//		ExceptionUtil.processException(e);
//		}
    }

    /**
     * 重命名文件
     * @param path 文件路径
     * @param oldName 旧文件名
     * @param newName 新文件名
     */
    public static void renameFile(String path,String oldName,String newName){
    	File oldfile=new File(path+"\\"+oldName);
        File newfile=new File(path+"\\"+newName);
        if(newfile.exists()){
            logger.debug(newName+"已经存在！");
        }else{
            oldfile.renameTo(newfile);
        }
    }
    /**
     * 删除文件
     * @param file
     */
    public static void deleteFile(File file){
    	if(null==file)
    		return;
    	if(file.exists()){
    		file.delete();
    	}
    }
    /**
     * 查找文件
     * @param valueOf
     * @return
     */
	public static File findFileByName(String name) {
		String path = getReportPath();
		File file = new File(path);
		if(file.isDirectory()){
			String[] names = file.list();
			for(int i=0; i<names.length; i++){
				String xml = names[i];
				if(xml.equals(name+".xml")){
					File returnFile = new File(path+xml);
					return returnFile;
				}
			}
		}
		return null;
	}

	/**
	 *
	 * 方法功能:创建文件夹
	 * 更新时间:2011-5-12, 作者:johnny
	 * @param string
	 */
	public static void createDirIfNotExist(String path) {
		File dirFile = new File(path);
	    boolean bFile   = dirFile.exists();
	    if(bFile == true ){
	    	logger.debug("The folder exists.");
	    }else{
	    	logger.debug("The folder do not exist,now trying to create a one...");
	    	bFile = dirFile.mkdirs();
	    }
	    if(bFile == true ){
//	    	logger.debug("Create successfully!");
//	    	logger.debug("创建文件夹");
	    }
	}

	public static void ifNotExistMkdir() {
		createDirIfNotExist(SystemType.DATA_UPLOAD_PATH);
//		createDirIfNotExist(SystemType.DATA_BACKUP_PATH);
//		createDirIfNotExist(SystemType.DATA_CLIENT_PATH);
//		createDirIfNotExist(SystemType.DATA_ROLE_PATH);
	}

	/**
	 * 压缩ZIP
	 * @param path
	 * @param fileName
	 */
	public static void zip(String path,String fileName){
		try{
			File file = new File(path);
			File[] files = file.listFiles();
			FileOutputStream fos = new FileOutputStream(path+fileName);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
			BufferedInputStream bis = null;
			int size = 2048;
			byte[] data = new byte[size];
			for(int i=0; i<files.length; i++){
				FileInputStream fis = new FileInputStream(files[i]);
				bis = new BufferedInputStream(fis,size);
				ZipEntry zip = new ZipEntry(files[i].getName());
				zos.putNextEntry(zip);
				int count = 0;
				while((count=bis.read(data, 0, size))!=-1){
					zos.write(data, 0, count);
				}
				bis.close();
			}
			zos.close();
		}catch (Exception e) {
			ExceptionUtil.processException(e);
		}
	}

	/**
	 * 解压ZIP
	 */
	public static void unZip(String path,String fileName){
		try{
			int size = 2048;
			ZipFile zip = new ZipFile(path+fileName);
			Enumeration<?> enumer = zip.entries();
			while(enumer.hasMoreElements()){
				ZipEntry entry = (ZipEntry)enumer.nextElement();
				if(entry.isDirectory()){
					new File(path+entry.getName()).mkdir();
					continue;
				}
				BufferedInputStream bis = new BufferedInputStream(zip.getInputStream(entry));
				File file = new File(path + "\\zip\\" + entry.getName());
				File parent = file.getParentFile();
				if(null!=parent && !parent.exists()){
					parent.mkdirs();
				}
				int count = 0;
				byte[] data = new byte[size];
				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos,size);
				while((count=bis.read(data, 0, size))!=-1){
					bos.write(data, 0, count);
				}
				bos.flush();
				bos.close();
				bis.close();
			}
			zip.close();
		}catch (Exception e) {
			ExceptionUtil.processException(e);
		}
	}

	public static HSSFSheet getInterSheetData(File file) {
		String name = "前端消息类文本";
		HSSFWorkbook workBook = getWorkbook(file);
		for(int i=0; i<workBook.getNumberOfSheets(); i++){
			HSSFSheet sheet = workBook.getSheetAt(i);
			if(name.equals(sheet.getSheetName())){
				return sheet;
			}
		}
		return null;
	}
	/**
	 * 删除目录下的所有文件
	 * @param filepath
	 */
	public static void delDirectory(String filepath){
		File file = new File(filepath);
		if(file.exists() && file.isDirectory()){
			if(file.listFiles().length<=0){
				file.delete();
			}else{
				File[] files = file.listFiles();
				for(int i=0; i<files.length; i++){
					if(files[i].isDirectory()){
						delDirectory(files[i].getAbsolutePath());
					}else{
						files[i].delete();
					}
				}
			}
		}
	}

	public static HSSFSheet createInterExcel(String name) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(name);

		HSSFRow row = sheet.createRow(0);
		HSSFCell packageCell = row.createCell(0);
		HSSFCell classCell = row.createCell(1);
		HSSFCell titleCell = row.createCell(2);
		HSSFCell commentCell = row.createCell(3);
		HSSFCell zh_cnCell = row.createCell(4);
		HSSFCell en_usCell = row.createCell(5);
		packageCell.setCellValue("包名");
		classCell.setCellValue("类名");
		titleCell.setCellValue("代号");
		commentCell.setCellValue("注释");
		zh_cnCell.setCellValue("中文");
		en_usCell.setCellValue("英文");

		return sheet;
	}




}
